package com.example.alioss.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Service
public class AsyncRequestService {

    private static final String PRE_TOKEN = "accessToken:";

    @Autowired
    private RedisTemplate redisTemplate;

    @Async
    public Future<String> getValue() throws InterruptedException {
        while (true) {
            synchronized (this) {
                String msg = (String) redisTemplate.opsForValue().get(PRE_TOKEN);
                if (!StringUtils.isEmpty(msg)) {
                    String resultMsg = msg;
                    postValue("");
                    return new AsyncResult("redis:" + resultMsg);
                }
            }
            Thread.sleep(1000);
        }
    }

    public synchronized String postValue(String msg) {
        redisTemplate.opsForValue().set(PRE_TOKEN, msg, 60 * 60, TimeUnit.SECONDS);
        return msg;
    }
}
